package com.kedacom.demo.modularity.core;

import java.util.Locale;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * BusinessExceptionMapper，将业务类异常BusinessException序列化成json并封装为response返回
 * @author luocanfeng
 * @date 2013-8-23
 */
@Provider
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public Response toResponse(BusinessException exception) {
		// 打印异常日志
		logger.info("Occur exception {code: {}, message: {}}", exception.getCode(), exception.getMessage());

		BusinessExceptionEntity entity = BusinessExceptionEntity.fromBusinessException(exception);
		ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
		builder.type(MediaType.APPLICATION_JSON);
		builder.encoding("utf8");
		builder.language(Locale.SIMPLIFIED_CHINESE);
		builder.entity(entity);
		Response response = builder.build();
		return response;
	}

}
